from flask import Blueprint, jsonify, request, Response
from models import Employee
from extensions import db
from flask_login import login_required
import csv
from io import StringIO

employees_bp = Blueprint('employees', __name__)


@employees_bp.route('/employees', methods=['GET'])
@login_required
def get_employees():
    try:
        employees = Employee.query.all()
        serialized_employees = [employee.to_dict() for employee in employees]
        return jsonify(serialized_employees), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@employees_bp.route('/employees/<int:id>', methods=['GET'])
@login_required
def get_employee(id):
    try:
        employee = Employee.query.get_or_404(id)
        serialized_employee = employee.to_dict()
        return jsonify(serialized_employee), 200
    except Exception as e:
        return jsonify({'error': '员工编号不存在'}), 400


@employees_bp.route('/employees', methods=['POST'])
@login_required
def create_employee():
    try:
        data = request.get_json()
        existing_employee = Employee.query.get(data.get('employee_id'))
        if existing_employee:
            return jsonify({'error': '该员工编号已存在，请勿重复添加'}), 400

        new_employee = Employee(
            id=data.get('employee_id'),
            name=data.get('employee_name'),
            password=data.get('password'),
            level=data.get('level', 1),
            phone=data.get('phone'),
            salary=data.get('salary'),
            remark=data.get('remark')
        )
        db.session.add(new_employee)
        db.session.commit()
        return jsonify(new_employee.to_dict()), 201
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@employees_bp.route('/employees/<int:id>', methods=['PUT'])
@login_required
def update_employee(id):
    try:
        employee = Employee.query.get_or_404(id)
        data = request.get_json()

        new_employee_id = data.get('new_employee_id')
        if new_employee_id and int(new_employee_id) != employee.id:
            if Employee.query.get(new_employee_id):
                return jsonify({'error': '新员工编号已存在，请选择不同的编号。'}), 400
            employee.id = int(new_employee_id)

        employee.name = data.get('name')
        employee.password = data.get('password')
        employee.level = data.get('level')
        employee.phone = data.get('phone')
        employee.salary = data.get('salary')
        employee.remark = data.get('remark')

        db.session.commit()
        return jsonify(employee.to_dict()), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@employees_bp.route('/employees/<int:id>', methods=['DELETE'])
@login_required
def delete_employee(id):
    try:
        employee = Employee.query.get_or_404(id)
        db.session.delete(employee)
        db.session.commit()
        return jsonify({'message': '员工删除成功'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@employees_bp.route('/employees/count', methods=['GET'])
@login_required
def get_employee_count():
    try:
        count = Employee.query.count()
        return jsonify({'count': count}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400


@employees_bp.route('/employees/export/csv', methods=['GET'])
@login_required
def export_employees_csv():
    try:
        employees = Employee.query.all()
        output = StringIO()
        writer = csv.writer(output)
        writer.writerow(['id', 'name', 'password', 'level', 'phone', 'salary', 'remark'])
        for employee in employees:
            writer.writerow([employee.id, employee.name, employee.password, employee.level, employee.phone, employee.salary, employee.remark])
        output.seek(0)
        return Response(output, mimetype='text/csv', headers={'Content-Disposition': 'attachment; filename=employees.csv'}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 400
